package com.androidhive.twitterconnect;

import java.util.List;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.Vibrator;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	SharedPreferences sPref;
	private static Twitter twitter;
	private static RequestToken requestToken;

	private static SharedPreferences mSharedPreferences;
	private static ConnectionDetector cd;
	private static final String MY_SETTINGS = "my_settings";

	AlertDialogManager alert = new AlertDialogManager();
	private String username;
	final String SAVED_TEXT = "saved_text";

	@Override
	public void onCreate(Bundle savedInstanceState) {

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		Constants.btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
		Constants.btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
		Constants.btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
		Constants.refresh = (Button) findViewById(R.id.refresh);
		Constants.txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
		Constants.lblUpdate = (TextView) findViewById(R.id.lblUpdate);
		Constants.textUserID = (TextView) findViewById(R.id.textUserID);
		Constants.textViewTweetFeed = (TextView) findViewById(R.id.textViewTweetFeed);

		mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
		Constants.textViewTweetFeed.setText("");

		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);

		cd = new ConnectionDetector(getApplicationContext());

		//------------------------Check if Internet present----------------------------

		if (!cd.isConnectingToInternet()) {
			setContentView(R.layout.main1);
			AlertDialog.Builder internetWarning = new AlertDialog.Builder(this);
			internetWarning.setTitle("Connection Problems:");
			internetWarning.setMessage("No internet connection\n-exiting application.");
			internetWarning.setIcon(R.drawable.fail);
			internetWarning.setPositiveButton("Quit", new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int id) {

					android.os.Process.killProcess(android.os.Process.myPid());
				}

			});

			AlertDialog alert1 = internetWarning.create();
			alert1.show();

			Constants.btnLoginTwitter.setVisibility(View.GONE);
			Constants.lblUpdate.setVisibility(View.GONE);
			Constants.txtUpdate.setVisibility(View.GONE);
			Constants.btnUpdateStatus.setVisibility(View.GONE);
			Constants.refresh.setVisibility(View.GONE);
			Constants.btnLogoutTwitter.setVisibility(View.GONE);
			Constants.textUserID.setVisibility(View.GONE);

			return;
		}

		loadText();

		//-----TODO-------------------Check if twitter keys are set-------------------------

		if (Constants.TWITTER_CONSUMER_KEY.trim().length() == 0 || Constants.TWITTER_CONSUMER_SECRET.trim().length() == 0) {
			alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
			return;
		}

		//------------------------SetOnClickListener------------------------------------

		Constants.refresh.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {

				refresh();

			}});

		//------------btnLoginTwitter calls loginToTwitter() function---------------------

		Constants.btnLoginTwitter.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				loginToTwitter();
			}
		});

		//------------btnUpdateStatus calls updateTwitterStatus() function----------------

		Constants.btnUpdateStatus.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String status = Constants.txtUpdate.getText().toString();
				if (status.trim().length() > 0) {
					new updateTwitterStatus().execute(status);
				} else {
					Toast.makeText(getApplicationContext(), "Please enter status message", Toast.LENGTH_SHORT).show();
				}
			}
		});

		//------------btnLogoutTwitter calls logoutFromTwitter() function----------------

		Constants.btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				logoutFromTwitter();
			}
		});

		//------------Parse the uri to get oAuth Verifier----------------

		if (isTwitterLoggedInAlready()) {

			Constants.lblUpdate.setVisibility(View.VISIBLE);
			Constants.txtUpdate.setVisibility(View.VISIBLE);
			Constants.btnUpdateStatus.setVisibility(View.VISIBLE);
			Constants.refresh.setVisibility(View.VISIBLE);
			Constants.btnLogoutTwitter.setVisibility(View.VISIBLE);
			Constants.textUserID.setVisibility(View.VISIBLE);
			Constants.btnLoginTwitter.setVisibility(View.GONE);
			refresh();
		} else {

			Constants.btnLoginTwitter.setVisibility(View.VISIBLE);
			Constants.lblUpdate.setVisibility(View.GONE);
			Constants.txtUpdate.setVisibility(View.GONE);
			Constants.btnUpdateStatus.setVisibility(View.GONE);
			Constants.refresh.setVisibility(View.GONE);
			Constants.btnLogoutTwitter.setVisibility(View.GONE);
			Constants.textUserID.setVisibility(View.GONE);

			Uri uri = getIntent().getData();

			if (uri != null && uri.toString().startsWith(Constants.TWITTER_CALLBACK_URL)) {
				String verifier = uri.getQueryParameter(Constants.URL_TWITTER_OAUTH_VERIFIER);
				try {
					AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
					Editor e = mSharedPreferences.edit();

					e.putString(Constants.PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
					e.putString(Constants.PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());

					e.putBoolean(Constants.PREF_KEY_TWITTER_LOGIN, true);
					e.commit();

					Log.e("Twitter OAuth Token", "> " + accessToken.getToken());

					long userID = accessToken.getUserId();
					User user = twitter.showUser(userID);
					username = user.getName();
					Constants.textUserID.setText(username);
					saveText();

					// Displaying in xml ui
					Constants.lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
				} catch (Exception e) {
					// Check log for login errors
					Log.e("Twitter Login Error", "> " + e.getMessage());
				}

			}

		}

	}

	//------------Save textUserID in buffer----------------

	void saveText() {
		sPref = getPreferences(MODE_PRIVATE);
		Editor ed = sPref.edit();
		ed.putString(SAVED_TEXT, Constants.textUserID.getText().toString());
		ed.commit();

	}

	//------------Load textUserID from buffer----------------

	void loadText() {
		sPref = getPreferences(MODE_PRIVATE);
		String savedText = sPref.getString(SAVED_TEXT, "");
		Constants.textUserID.setText(savedText);
		Toast.makeText(this, "Login loaded", Toast.LENGTH_SHORT).show();
	}

	//------------Function to login twitter----------------

	private void loginToTwitter() {
		if (!isTwitterLoggedInAlready()) {
			ConfigurationBuilder builder = new ConfigurationBuilder();
			builder.setOAuthConsumerKey(Constants.TWITTER_CONSUMER_KEY);
			builder.setOAuthConsumerSecret(Constants.TWITTER_CONSUMER_SECRET);
			Configuration configuration = builder.build();

			TwitterFactory factory = new TwitterFactory(configuration);
			twitter = factory.getInstance();

			try {
				requestToken = twitter.getOAuthRequestToken(Constants.TWITTER_CALLBACK_URL);
				this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
			} catch (TwitterException e) {
				e.printStackTrace();
			}
		} else {

			Constants.lblUpdate.setVisibility(View.VISIBLE);
			Constants.txtUpdate.setVisibility(View.VISIBLE);
			Constants.btnUpdateStatus.setVisibility(View.VISIBLE);
			Constants.refresh.setVisibility(View.VISIBLE);
			Constants.btnLogoutTwitter.setVisibility(View.VISIBLE);
			Constants.textUserID.setVisibility(View.VISIBLE);
			Constants.btnLoginTwitter.setVisibility(View.GONE);
			Toast.makeText(getApplicationContext(), "Already Logged into twitter", Toast.LENGTH_LONG).show();
		}
	}

	//------------Function to update status----------------

	class updateTwitterStatus extends AsyncTask<String, String, String> {

		// Before starting background thread Show Progress Dialog

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			Constants.pDialog = new ProgressDialog(MainActivity.this);
			Constants.pDialog.setMessage("Updating to twitter...");
			Constants.pDialog.setIndeterminate(false);
			Constants.pDialog.setCancelable(false);
			Constants.pDialog.show();
		}

		//------------Getting Places JSON----------------

		protected String doInBackground(String... args) {
			Log.d("Tweet Text", "> " + args[0]);
			String status = args[0];
			try {
				ConfigurationBuilder builder = new ConfigurationBuilder();
				builder.setOAuthConsumerKey(Constants.TWITTER_CONSUMER_KEY);
				builder.setOAuthConsumerSecret(Constants.TWITTER_CONSUMER_SECRET);

				String access_token = mSharedPreferences.getString(Constants.PREF_KEY_OAUTH_TOKEN, "");
				String access_token_secret = mSharedPreferences.getString(Constants.PREF_KEY_OAUTH_SECRET, "");

				AccessToken accessToken = new AccessToken(access_token, access_token_secret);
				Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);

				twitter4j.Status response = twitter.updateStatus(status);

				Log.d("Status", "> " + response.getText());
			} catch (TwitterException e) {
				Log.d("Twitter Update Error", e.getMessage());
			}
			return null;
		}

		//------------update UI from background thread----------------

		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			Constants.pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getApplicationContext(), "Status tweeted successfully", Toast.LENGTH_SHORT).show();
					Constants.txtUpdate.setText("");
				}
			});

		}

	}

	//------------Function to logout from twitter----------------

	private void logoutFromTwitter() {

		Constants.textViewTweetFeed.setText("");

		Editor e = mSharedPreferences.edit();
		e.remove(Constants.PREF_KEY_OAUTH_TOKEN);
		e.remove(Constants.PREF_KEY_OAUTH_SECRET);
		e.remove(Constants.PREF_KEY_TWITTER_LOGIN);
		e.commit();

		Constants.btnLoginTwitter.setVisibility(View.VISIBLE);
		Constants.lblUpdate.setVisibility(View.GONE);
		Constants.txtUpdate.setVisibility(View.GONE);
		Constants.btnUpdateStatus.setVisibility(View.GONE);
		Constants.refresh.setVisibility(View.GONE);
		Constants.btnLogoutTwitter.setVisibility(View.GONE);
		Constants.textUserID.setVisibility(View.GONE);

	}

	//------------user already logged check----------------

	private boolean isTwitterLoggedInAlready() {
		// return twitter login status from Shared Preferences
		return mSharedPreferences.getBoolean(Constants.PREF_KEY_TWITTER_LOGIN, false);
	}

	//------------Function to resume----------------
	protected void onResume() {
		super.onResume();
	}

	private void refresh(){
		
		

			String tweets = "";

			ConfigurationBuilder build = new ConfigurationBuilder();
			build.setOAuthConsumerKey(Constants.TWITTER_CONSUMER_KEY);
			build.setOAuthConsumerSecret(Constants.TWITTER_CONSUMER_SECRET);
			build.setOAuthAccessToken(mSharedPreferences.getString(Constants.PREF_KEY_OAUTH_TOKEN, ""));
			build.setOAuthAccessTokenSecret(mSharedPreferences.getString(Constants.PREF_KEY_OAUTH_SECRET, ""));

			Configuration cfg = build.build();
			TwitterFactory fct = new TwitterFactory(cfg);
			Twitter twatter = fct.getInstance();

			//------------------------Get HomeTimeLine From Twitter------------------

			try {
				List<Status> st = twatter.getHomeTimeline();
				for (int i = 0; i < 16; i++) {
					tweets = tweets + "\n@" + st.get(i).getUser().getName() + " " + st.get(i).getCreatedAt() + "\n" + st.get(i).getText() + "\n";
				}
				Constants.textViewTweetFeed.setText(tweets);
			} catch (TwitterException e) {
				e.printStackTrace();

			}

			Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			long milliseconds = 1000;
			v.vibrate(milliseconds);

		
		
	}

}
